/*
** SMSE2K Driver Interface, take 6.
**
**
** TODOS:
** - Possibly move driver factory controls out of here?
** - Lookup file formats via the driver factory.
*/


#include "smse2kincludes.h"

static CDriverFactory* factories[256];
static int factorycount = 0;

// move this later. currently this and the API require it
extern int SMSE_IsInDebugMode();

/********************************************************************************
** RegisterDriverFactory: Registers a CDriverFactory into the driver interface.
** This is done on construction of said class.
********************************************************************************/
void RegisterDriverFactory(CDriverFactory* factory) {
	if (!factory) return;

	if (factory->GetInterfaceVersion() > DRIVER_INTERFACE_CURRENT_VERSION) {
		Msg("Couldn't register driver factory for device %s: Invalid version %d, check source for problems\n",
					factory->GetName(), factory->GetInterfaceVersion());
		return;
	}

	Msg("Added new driver %s. (Interface version %d)\n",factory->GetName(),factory->GetInterfaceVersion());
	factories[factorycount] = factory;
	factorycount ++;
}

/*************************************************************************
** DriverFactory: Creates a new driver interface.
*************************************************************************/
IDriver* DriverFactory (const char* name) {
	int dbgmode = SMSE_IsInDebugMode();
	for (int i=0;i<factorycount;i++) {
		if (!strcmpi(factories[i]->GetName(),name)) {
			if (factories[i]->IsTestDriver()) {
				if (dbgmode == 1) return factories[i]->Init();
				else Msg("Testdriver cannot be loaded because SMSE2K is not in debug mode\n");
			} else return factories[i]->Init();
		}
	}

	return NULL;
}

IDriver* DriverFactory_CreateDriverByExtension(const char* ext) {

	int dbgmode = SMSE_IsInDebugMode();
	for (int i=0;i<factorycount;i++) {
		if (factories[i]->SupportsFileType(ext)) {
			Msg("Factory %d supports filetype\n",i);
			if (factories[i]->IsTestDriver()) {
				if (dbgmode == 1) return factories[i]->Init();
				else Msg("Testdriver cannot be loaded because SMSE2K is not in debug mode\n");
			} else return factories[i]->Init();
		}
		Msg("Checked factory %d\n",i);
	}

	return NULL;

}

/*******************************************************************
** OutputDriverList: Dumps all known drivers to the output buffer
*******************************************************************/
void OutputDriverList() {
	Msg("Drivers currently registered to DriverFactory:\n");
	for (int i=0;i<factorycount;i++) {
		Msg("%d. %s: %s\n",i+1,factories[i]->GetName(),factories[i]->GetDescription());
	}
}